package com.airforce.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/5/4.
 */
public class IpUtils {
    private static final Pattern ipPattern = Pattern.compile("([0-9]{1,3}\\.){3}[0-9]{1,3}");

    public IpUtils() {
    }

    public static String getClientIP(HttpServletRequest request) {
        if(request == null) {
            return null;
        } else {
            String xff = request.getHeader("X-Forwarded-For");
            String ip = getClientIPFromXFF(xff);
            if(ip != null) {
                return ip;
            } else {
                ip = request.getHeader("Proxy-Client-IP");
                if(isValidIP(ip)) {
                    return ip;
                } else {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                    if(isValidIP(ip)) {
                        return ip;
                    } else {
                        ip = request.getRemoteAddr();
                        return ip;
                    }
                }
            }
        }
    }

    private static String getClientIPFromXFF(String xff) {
        if(xff != null && xff.length() != 0) {
            String[] ss = xff.split(",");
            String[] arr$ = ss;
            int len$ = ss.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                String ip = arr$[i$];
                ip = ip.trim();
                if(isValidIP(ip)) {
                    return ip;
                }
            }

            return null;
        } else {
            return null;
        }
    }

    private static boolean isValidIP(String ip) {
        return ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)?ipPattern.matcher(ip).matches():false;
    }
}
